package com.lopo.mail;

import cn.hutool.core.io.FileUtil;
import org.apache.tomcat.util.http.fileupload.MultipartStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.xml.stream.events.Characters;
import java.io.File;
import java.nio.charset.Charset;

@Component
public class SmtpMessageUtils {
    @Autowired
    private JavaMailSender mailSender; //自动注入的Bean

    @Value("${spring.mail.username}")
    private String userName; //读取配置文件中的参数

 private static String test; //邮件主题

    //邮件主题
    static {
        ClassPathResource classPathResource = new ClassPathResource("email.html");
        test = FileUtil.readString(classPathResource.getPath(), Charset.defaultCharset());
    }

    /**
     * 普通邮件发送
     *
     * @throws MessagingException
     */
    public void sendSimpleMail1() throws MessagingException {
        // 创建模板消息类
        MimeMessage message = mailSender.createMimeMessage();
        // 创建模板消息附带信息
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 设置发件人邮箱
        helper.setFrom(userName);
        // 设置收件人邮箱
        helper.setTo(
            "lopox@qq.com");
        // 设置邮件标题
        helper.setSubject("EP-Link Verification Code");
        // 设置邮件主体内容， true 表示带有附件或html
        helper.setText(String.format(test, "123456"), true);
        // 发送消息
        mailSender.send(message);
    }
}

